import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild, CanLoad, Router, ActivatedRouteSnapshot, RouterStateSnapshot , Route} from '@angular/router';
import { LoginService } from './login.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGurdService implements CanActivate, CanActivateChild, CanLoad {

  constructor(private router: Router, private loginService: LoginService) { }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
     const url = state.url;
     return this.checkLogin(url);
  }
  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const url = state.url;
    return this.checkLogin(url);
 }
 canLoad (route: Route): boolean {
  const url = `/${route.path}`;
  return this.checkLogin(url);
}
  checkLogin(url: string): boolean {
     if(this.loginService.isLoginIn()){
        return true
     }
     this.loginService.redirectUrl = url;
     this.router.navigate(['/login']);
     return false;
  }
}
